package org.deng.learn.zookeeper.simple;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * @Author DengLibin
 * @Date 19-5-12
 * @Time 下午4:54
 * @Desc 服务器类
 */
public class Server {
    //服务器集群
    private static String servers = "node2:2181,node3:2181,node4:2181";
    //zookeeper客户端
    private  ZooKeeper client;

    private String zkNodeName;//该服务器在zookeeper上的节点名称 全路径
    private String data; //数据

    private volatile  boolean isStart = false; //服务器是否开启

    public Server(String zkNodeName, String data) {
        this.zkNodeName = zkNodeName;
        this.data = data;
    }

    /**
     * 开启服务器(保持进程不结束,保持和zookeeper的连接)
     */
    public void start(){
        new Thread(()->{
            try {
                connectZookeeper(); //连接到zookeeper
                registerToZookeeper(); //注册到zookeeper
                isStart = true;
                while (isStart){
                    //服务器自己的业务
                    Thread.sleep(1000 * 1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();
    }

    /**
     * 停止服务器
     */
    public void stop() throws InterruptedException {
        isStart = false;
        client.close();
    }
    /**
     * 连接到zookeeper
     * @throws IOException
     */
    private    void connectZookeeper() throws IOException {
        client = new ZooKeeper(servers, 2 * 1000, event -> {

        });
    }

    /**
     * 注册到zookeeper
     */
    private   void registerToZookeeper() throws KeeperException, InterruptedException {
        createServersNode();
        client.create(zkNodeName, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL); //临时的带序号的节点(断开连接后删除掉)
    }

    /**
     * 没有servers节点就创建一个
     */
    private void createServersNode(){
        try {
            Stat stat = client.exists("/servers", true);
            if(stat == null){
                client.create("/servers", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT);
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



    public String getZkNodeName() {
        return zkNodeName;
    }

    public void setZkNodeName(String zkNodeName) {
        this.zkNodeName = zkNodeName;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}
